<template>
  <div class="map-container"
       ref="map">
    <!-- <keep-alive> -->
    <el-row type="flex"
            class="row-bg"
            justify="space-around">
      <el-col :span="23">
        <transition name="fade-transform">
          <el-tabs v-model="tabsInfo.activeName"
                   type="card"
                   @tab-remove="handleTabRemove">
            <el-tab-pane v-for="(item,index) in this.tagInfo"
                         :label="item.userName"
                         :name="item.tagId"
                         :key="index"
                         closable>
              <el-collapse v-model="tabsInfo.activeCollapseName">
                <el-collapse-item title="标签信息"
                                  name="1">
                  <el-row :gutter="20">
                    <el-col :span="8">姓名：{{item.userName}}</el-col>
                    <el-col :span="8">ID：{{item.tagId}}</el-col>
                    <el-col :span="8">类别：{{item.userPost}}</el-col>
                    <!-- <el-col :span="8">区域：{{item.areaName}}</el-col> -->
                  </el-row>
                </el-collapse-item>
                <el-collapse-item title="历史轨迹"
                                  name="2">
                  请选择要查询的时间范围：
                  <!-- <el-date-picker :disabled="picker_disabled" -->
                  <el-date-picker v-model="tabsInfo.PositionTS"
                                  @change="dateConfirmed"
                                  type="datetimerange"
                                  start-placeholder="开始时间"
                                  end-placeholder="结束时间"
                                  :picker-options="tabsInfo.pickerOptions"
                                  :default-time="['09:00:00','17:00:00']"
                                  value-format="timestamp">
                    <!-- :picker-options="pickerOptions" -->
                  </el-date-picker>
                  <el-button type="primary"
                             :disabled="!tabsInfo.picker_disabled"
                             :loading="tabsInfo.confirmLoading"
                             @click="getPositionTrack">提交</el-button>
                  <el-button type="danger"
                             size="mini"
                             v-if="tabsInfo.isSliderActive"
                             @click="handleTrackRemove">关闭<i class="el-icon-circle-close el-icon--right"></i></el-button>
                  <transition name="fade-transform">
                    <el-row v-if="tabsInfo.isSliderActive&&show3D&&show2D"
                            :gutter="10">
                      <el-col :span="18">
                        <!-- <el-slider v-model="tabsInfo.time"
                                   :step="parseInt((tabsInfo.positionTimes[tabsInfo.positionTimes.length-1] -tabsInfo.positionTimes[0]) /120)"
                                   :format-tooltip="formatTooltip"
                                   :min="tabsInfo.positionTimes[0]"
                                   :max="tabsInfo.positionTimes[tabsInfo.positionTimes.length-1]"></el-slider> -->
                        <el-slider v-model="tabsInfo.time"
                                   :format-tooltip="formatTooltip"
                                   :min="tabsInfo.positionTimes[0]"
                                   :max="tabsInfo.positionTimes[tabsInfo.positionTimes.length-1]"></el-slider>
                      </el-col>
                      <el-col :span="2">
                        <el-checkbox v-model="tabsInfo.showTrack"
                                     class="showTrack">显示轨迹</el-checkbox>
                      </el-col>

                      <!-- <el-col :span="2">
                        <el-button type="danger"
                                   size="mini"
                                   @click="handleTrackRemove">关闭<i class="el-icon-circle-close el-icon--right"></i></el-button>
                      </el-col> -->

                    </el-row>
                  </transition>

                </el-collapse-item>
              </el-collapse>
            </el-tab-pane>
          </el-tabs>
        </transition>

      </el-col>
    </el-row>
    <el-row>
      <map-two v-show="show2D"
               ref="map2D"
               :height="height"
               :show2D="show2D"
               :width="width"
               :tag-info="tagInfo"
               :tag-position="tagPosition"
               :warning-info="warningInfo"
               :tabs-info="tabsInfo"></map-two>
    </el-row>
    <el-row>
      <map-three v-show="show3D"
                 ref="map3D"
                 class='map3D'
                 :show3D="show3D"
                 :height="height"
                 :width="width"
                 :tag-info="tagInfo"
                 :tag-position="tagPosition"
                 :warning-info="warningInfo"
                 :tabs-info="tabsInfo"></map-three>
    </el-row>

    <div class='btn1'>
      <el-button type="primary"
                 class='btn2'
                 @click="handle2D"
                 circle>
        <svg-icon icon-class="2D" />
      </el-button>
      <el-button type="success"
                 class='btn2'
                 @click="handle3D"
                 circle>
        <svg-icon icon-class="3D" />
      </el-button>
    </div>
    <!-- </keep-alive> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import MapThree from '@/components/Map/MapThree'
import MapTwo from '@/components/Map/MapTwo'
// import resize from './mixins/resize'

import { isEqual, parseTime } from '@/utils'
import { getTagPositionTrack, listCurrentTags } from '@/api/map'

export default {
  name: 'Map',
  // mixins: [resize],

  data() {
    return {
      width: '100%',
      height: 'calc(100vh - 106px)',
      show3D: false,
      show2D: true,
      tabsInfo: {
        activeCollapseName: ['1'],
        activeName: 'error',
        PositionTS: '',
        params_track: {
          beginPositionTS: null,
          endPositionTS: null,
          tagId: null
        },
        showTrack: true,
        trackCreated: false,
        time: null,
        isSliderActive: false,
        positionTracks: null,
        positionTimes: null,
        confirmLoading: false,
        picker_disabled: false,
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一分钟',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 60 * 1000)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一小时',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一天',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            }
          ]
        }
      },
      tagInfo: null,
      tagPosition: [],
      warningInfo: null
    }
  },
  methods: {
    handleTrackRemove() {
      this.tabsInfo.isSliderActive = false
      this.tabsInfo.PositionTS = null
      this.tabsInfo.showTrack = false
      this.tabsInfo.picker_disabled = false
      this.tabsInfo.activeCollapseName = ['']
      // this.tabsInfo.positionTracks=[]
      // this.tabsInfo.positionTimes=[]
      // this.$refs.map3D.removeTrackAnimation()
    },
    getPositionTrack() {
      // this.tabsInfo.showTrack = false
      this.tabsInfo.confirmLoading = true
      this.tabsInfo.params_track.beginPositionTS = this.tabsInfo.PositionTS[0]
      this.tabsInfo.params_track.endPositionTS = this.tabsInfo.PositionTS[1]
      this.tabsInfo.params_track.tagId = this.tabsInfo.activeName
      getTagPositionTrack(this.tabsInfo.params_track).then(
        r => {
          console.log(r)
          this.tabsInfo.time = r.timestamp[0]
          console.log(this.tabsInfo.time)
          // let j = r.length >= 10000 ? Math.floor(r.length / 10000) : 1
          this.tabsInfo.positionTracks = r.position
          this.tabsInfo.positionTimes = r.timestamp
          console.log(this.tabsInfo.positionTimes.length)
          this.tabsInfo.confirmLoading = false
          this.tabsInfo.isSliderActive = true
        },
        e => {
          this.tabsInfo.confirmLoading = false
          console.log(e)
          console.log('fail')
        }
      )
    },
    dateConfirmed(val) {
      console.log(val)
      this.tabsInfo.picker_disabled = val ? true : false
      console.log(this.tabsInfo.picker_disabled)
    },
    handleTabRemove(tab) {
      console.log(tab)
      this.tabsInfo.activeName = 'error'
    },
    formatTooltip(val) {
      if (val) {
        return parseTime(val)
      }
    },
    handle2D() {
      this.show3D = false
      this.show2D = true
      console.log(this.$refs.map2D)
      this.$nextTick(() => {
        this.$refs.map2D.$_resizeHandler()
      })
    },
    handle3D() {
      this.show2D = false
      this.show3D = true
      console.log(this.$refs.map3D)

      this.$nextTick(() => {
        this.$refs.map3D.$_resizeHandler()
      })
    },
    initWebsocket() {
      if ('WebSocket' in window) {
        this.websocket = new WebSocket(
          'ws://' + process.env.VUE_APP_BASE_API.substr(7) + '/websocket'
        )
      } else {
        alert('Not support websocket')
      }
      //连接发生错误的回调方法
      this.websocket.onerror = this.websocketOnError

      //连接成功建立的回调方法
      this.websocket.onopen = this.websocketOnOpen

      //接收到消息的回调方法
      this.websocket.onmessage = this.websocketOnMessage

      this.websocket.onclose = this.websocketOnClose
    },
    websocketOnError() {
      console.log('WebSocket连接发生错误')
    },
    websocketOnOpen(e) {
      console.log('WebSocket连接成功')
      console.log(e)
    },
    websocketOnMessage(e) {
      if (e.data.length >= 5) {
        let r = JSON.parse(e.data)
        for (let i in r.tags) {
          for (let j in this.tagInfo) {
            if (r.tags[i].id === this.tagInfo[j].tagId) {
              this.$set(
                this.tagPosition[j].position,
                0,
                r.tags[i].smoothedPosition[0]
              )
              this.$set(
                this.tagPosition[j].position,
                1,
                r.tags[i].smoothedPosition[1]
              )
            }
          }

          // this.tagPosition[i].position = [...this.tagPosition[i].position]

          // this.tagPosition[i].position = r.tags[i].smoothedPosition.slice(0, 2)
        }
        // }
        if (r.total === 1) {
          console.log(r)
          this.warningInfo = r.taginfos[0]
        }
      }
    },
    websocketOnClose() {
      console.log('websocket成功断开')
      this.websocket.close()
    }
  },
  created() {
    this.tagInfo = [
      {
        tagId: 'c6f39ab751b8',
        userName: '123',
        color: '#FFBF00',
        userPost: '手推车',
        id: 4,
        timeOutLoading:0,
      },
      {
        tagId: 'e7979e64a05c',
        userName: '456',
        color: '#FFBF00',
        userPost: '访客',
        id: 7,
        timeOutLoading:0,
      }
    ]
    setTimeout(() => {
      this.tagInfo.push({
        tagId: 'd948455dba4f',
        userName: 'youke1',
        color: '#FFBF00',
        userPost: '访客',
        id: 2,
        timeOutLoading:0,
      })
    }, 1000)
    for (let i in this.tagInfo) {
      this.tagPosition.push({
        name: this.tagInfo[i].tagId,
        position: [16.185, 12.48]
      })
    }
    // listCurrentTags().then(r => {
    //   this.tagInfo = r
    //   this.$nextTick(() => {
    //     for (let i in r) {
    //       this.tagPosition.push({
    //         name: r[i].tagId,
    //         position: [16.185, 12.48]
    //       })
    //     }
    //   })
    // })
    // this.initWebsocket()
  },
  mounted() {
    // setTimeout(()=>{
    //   this.warningInfo={id:'d948455dba4f',userName:'访客01',status:1,area:'234'}
    //         console.log(this.warningInfo)
    // },3000)
    // setTimeout(()=>{
    //   this.warningInfo={id:'c6f39ab751b8',status:2,area:'234'}
    //         console.log(this.warningInfo)
    // },4000)
    // setTimeout(()=>{
    //   this.warningInfo={id:'d948455dba4f',status:3,area:'234'}
    //         console.log(this.warningInfo)
    // },6000)
    // setTimeout(()=>{
    //   this.warningInfo={id:'d948455dba4f',status:2,area:'234'}
    //         console.log(this.warningInfo)
    // },12000)
    // setTimeout(()=>{
    //   this.warningInfo={id:'d948455dba4f',status:3,area:'234'}
    //         console.log(this.warningInfo)
    // },18000)
    // setTimeout(()=>{
    //   this.warningInfo={id:'d948455dba4f',status:2,area:'234'}
    //         console.log(this.warningInfo)
    // },21000)
    // console.log(process.env.VUE_APP_BASE_API.substr(7))
  },
  watch: {
    warningInfo: function(val, oldVal) {
      console.log(this.warningInfo)
      if (!isEqual(val, oldVal)) {
        if (this.warningInfo.status === 0) {
          this.$notify({
            title: '警报解除',
            message: this.warningInfo.name + '回到了' + this.warningInfo.area,
            type: 'success',
            customClass: 'success-area',

            duration: 5000
          })
          // this.activeName = this.warningInfo.name
          // this.warningInfo.splice(i, i)
        } else if (this.warningInfo.status === 1) {
          this.$notify({
            title: '警报',
            message: this.warningInfo.name + '进入了' + this.warningInfo.area,
            type: 'warning',
            customClass: 'warning-area',

            duration: 5000
          })
          

          let url =
            'http://111.229.7.173:8000/api/v1.0/service/location?content=' +
            this.warningInfo.name +
            '您已非法闯入库房请退出'
          this.$jsonp(url).then(e => {
            console.log(e)
          })

          // this.activeName = this.warningInfo.name
          // this.warningInfo.splice(i, i)
        } else if (this.warningInfo.status === 2) {
          this.$notify({
            title: 'SOS',
            message: this.warningInfo.name + '按键求救',
            customClass: 'warning-sos',
            type: 'warning',
            duration: 5000
          })
          // this.activeName = this.warningInfo.name
        } else if (this.warningInfo.status === 3) {
          this.$notify({
            title: 'SOS解除',
            message: this.warningInfo.name + '取消请求',
            customClass: 'success-sos',
            type: 'success',
            duration: 5000
          })
          // this.activeName = this.warningInfo.name
        }
      }
    }
  },
  components: { MapThree, MapTwo },
  // components: { MapThree },
  computed: {
    ...mapGetters(['name'])
  }
}
</script>
<style>
.success-area {
  background: rgb(24, 245, 4) !important;
}
.warning-area {
  background: rgb(245, 229, 4) !important;
}
.warning-sos {
  background: rgb(233, 10, 10) !important;
}
.success-sos {
  background: rgb(4, 245, 4) !important;
}
.el-notification__content {
  color: black;
}
</style>
<style lang="scss" scoped>
@import '~@/styles/mixin.scss';
@import '~@/styles/variables.scss';
.map-container {
  position: relative;
  width: '100%';
  height: '100%';
  // height: calc(100vh +150px);
}
.btn1 {
  position: fixed;
  bottom: 40px;
  right: 30px;
  // z-index: -1;
  // right:calc(100% - #{$sideBarWidth});
  // left: calc(100% - #{$sideBarWidth});
}
.btn2 {
  font-size: 35px;
}
.showTrack {
  margin: 5px, 20px;
}
</style>
